package com.czxy.controller;

import com.czxy.vo.UploadResult;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 文件上传
 *
 * @author likk
 * @create 2018/7/24
 */
@RestController
@Slf4j
public class FileUploadController {

    @Value("${FILE_SERVER_URL}")
    private String FILE_SERVER_URL;//文件服务器地址

    @Autowired
    private FastFileStorageClient storageClient;

    @RequestMapping(value = "upload")
    public UploadResult upload(MultipartFile file){
        if (file == null){
            return new UploadResult(false, "上传失败");
        }
        //取文件的扩展名
        String originalFilename = file.getOriginalFilename();
        String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);

        try {
            StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), extName, null);
            String path = storePath.getFullPath(); // 获取完整的路径，包括组
            //拼接返回的 url 和 ip 地址，拼装成完整的 url
            String url = FILE_SERVER_URL + path;

            return new UploadResult(true,url);
        } catch (IOException e) {
            e.printStackTrace();
            return new UploadResult(false, "上传失败");
        }
    }

}
